package com.capinfo.commons.project.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.web.servlet.ModelAndView;

import com.capinfo.commons.project.model.region.Region;


public class RegionUtils {
	
	
	/**
	 * 初始化区域级联下拉框时需要的数据
	 * @param viewModel  保存数据
	 * @param region  初始化区域
	 */
	public static void initScopeIds(Map<String, Object> viewModel, Region region) {
		String specifiedScopeIds = "[]";
		
		specifiedScopeIds = traceRegionId(region).toString();
		
		viewModel.put("specifiedScopeIds", specifiedScopeIds);  
	    
		viewModel.put("dataScopeRootId", (new Region()).getRootId());
	}
	
	/**
	 * 初始化区域级联下拉框时需要的数据
	 * @param mav  保存数据
	 * @param region  初始化区域
	 */
	public static void initScopeIds(ModelAndView mav, Region region) {
		String specifiedScopeIds = "[]";
		
		specifiedScopeIds = traceRegionId(region).toString();
		
		mav.addObject("specifiedScopeIds", specifiedScopeIds);  
	    
		mav.addObject("dataScopeRootId", (new Region()).getRootId());
	}
	
	private static List<Long> traceRegionId(Region region) {
		List<Long> regionIdList = new ArrayList<Long>();

		regionIdList.add(region.getId());
		//generalService.fetchLazyProperty(userDataScope, "parent");
		try{
			if( !Region.ROOT_ID.equals(region.getId()) ){
				Region parent = region.getParent();
				if( null != parent && null != parent.getId() && 0 != parent.getId() && -1 != parent.getId()) {
					regionIdList.addAll(0, traceRegionId(parent));
				}
			}
		} catch(Exception e) {}
		
		return regionIdList;
	}
}
